package com.atguigu.srb.core.config;



import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.Duration;


/*
    两个方法互不干扰，第一个方法初始化设置键和值的序列化器
    这样用redis保存数据就不会保存2进制
 */
@Configuration
public class RedisConfig {

    @Resource
    RedisTemplate redisTemplate;

    //当前类对象初始化后并完成依赖注入  给装配的redisTemplate配置键和值的序列化器
    //手动写缓存
    @PostConstruct
    public void init(){
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    }


    @Bean
    //引入了Commons-pool2依赖  项目启动时会启动初始化redis连接工厂
    public CacheManager cacheManager(LettuceConnectionFactory factory){
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()//设置默认配置
                .entryTtl(Duration.ofMinutes(600))//设置过期时间
                .serializeKeysWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair
                        .fromSerializer(new GenericJackson2JsonRedisSerializer()))
                ;
        //1、创建缓存管理器对象：
        return RedisCacheManager
                .builder(factory)//配置redis连接工厂
                .cacheDefaults(config)//缓存管理器 管理缓存的配置(键值序列化器、缓存过期时间、空值是否缓存)
                .build();

    }
}
